/**
 * 文件上传中间件
 */
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { PROJECTS_DIR } = require('../utils/constants');
const { generateId } = require('../utils/helpers');
const { readProjectsIndex } = require('../services/projectService');

// 配置multer存储
const storage = multer.diskStorage({
    destination: async (req, file, cb) => {
        const projectId = req.params.id;
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === projectId);
        
        if (!projectMeta) {
            return cb(new Error('项目不存在'));
        }
        
        const modelsDir = path.join(PROJECTS_DIR, projectMeta.path, 'models');
        await fs.mkdir(modelsDir, { recursive: true });
        cb(null, modelsDir);
    },
    filename: (req, file, cb) => {
        // 使用模型ID作为文件名，避免中文乱码
        const modelId = generateId('model');
        const ext = path.extname(file.originalname);
        
        // 将modelId存储在req中，供后续使用
        if (!req.modelIds) {
            req.modelIds = {};
        }
        req.modelIds[file.fieldname] = modelId;
        
        cb(null, `${modelId}${ext}`);
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 50 * 1024 * 1024 // 限制50MB
    },
    fileFilter: (req, file, cb) => {
        // 前端已经保证文件名编码正确，后端只需验证格式
        const allowedExts = ['.glb', '.gltf', '.obj', '.fbx', '.stl'];
        const ext = path.extname(file.originalname).toLowerCase();
        
        if (allowedExts.includes(ext)) {
            console.log(`✅ [Upload] 接收文件: ${file.originalname}`);
            cb(null, true);
        } else {
            cb(new Error(`不支持的文件格式: ${ext}，仅支持 ${allowedExts.join(', ')}`));
        }
    }
});

module.exports = upload;

